package com.esunrising.clickhouse.controller;

import com.alibaba.fastjson.JSONObject;
import com.esunrising.clickhouse.dto.emp;
import com.esunrising.clickhouse.utils.ClickhouseUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/demo2")
public class Demo2Controller {

    @PostMapping("/index")
    public JSONObject index(@RequestBody String param){
        JSONObject result = new JSONObject();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = ClickhouseUtil.getConnection();

            if(conn != null){
                String sql = "select id, name, hiredate, salary from emp";
                pstmt = conn.prepareStatement(sql);

                rs = pstmt.executeQuery();

                List<emp> empList = new ArrayList<>();
                while (rs.next()){
                    empList.add(new emp(rs.getInt("id"),rs.getString("name"), rs.getDate("hiredate"), rs.getDouble("salary")));
                }

                result.put("code", 200);
                result.put("msg", "查询成功");
                result.put("size", empList.size());
                result.put("data", empList);
            }else{
                result.put("code", 500);
                result.put("msg", "数据库连接失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "发生错误："+e.getMessage());
        } finally {
            ClickhouseUtil.close(rs, pstmt, conn);
        }


        return result;
    }
}
